package com.example.cc.client.utils;

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

/**
 * 封装 常用的 HTTP请求，简化 RESTFul API的调用
 */
public class HttpUtil {

    private static final RestTemplate restTemplate = new RestTemplate();

    // 简化 GET请求，返回字符串类型的结果
    public static String getString(String url) {
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        return response.getBody();
    }

    // 使用泛型和exchange()来实现GET请求，支持任意响应类型
    public static <T> T get(String url, Class<T> responseType) {
        ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.GET, null, responseType);
        return response.getBody();
    }

    // 通用 POST 方法，支持任意类型的请求体和响应类型
    public static <T> T post(String url, Object body, Class<T> responseType) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> requestEntity = new HttpEntity<>(body, headers);
        ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, responseType);
        return response.getBody();
    }

    // PUT 方法，支持任意类型的请求体
    public static void put(String url, Object request) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> entity = new HttpEntity<>(request, headers);
        restTemplate.exchange(url, HttpMethod.PUT, entity, Void.class);
    }

    // DELETE 请求
    public static void delete(String url) {
        restTemplate.exchange(url, HttpMethod.DELETE, null, Void.class);
    }

    /**
     * 通用的exchange方法，支持任意HTTP方法、请求体、响应类型、路径变量和查询参数。
     */
    public static <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType,
                                                 Object... uriVariables) {
        return restTemplate.exchange(url, method, requestEntity, responseType, uriVariables);
    }

    // 如果需要支持带有URI模板变量的复杂场景，可以添加如下方法：
    public static <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity,
                                                 ParameterizedTypeReference<T> typeRef, Object... uriVariables) {
        return restTemplate.exchange(url, method, requestEntity, typeRef, uriVariables);
    }
}
